<?php
if (!defined('IN_ZWS')) exit();

class AddArticleModel extends Model {
	protected $tableName = 'Article';
	protected $_validate = array(
		array('res', '0,2', '资源类型选择错误！', 1, 'between'),
		array('gpid', 'checkGroup', '非法分组，请重新选择！', 1, 'callback'),
		array('gdid', 'checkGrade', '非法年级，请重新选择！', 1, 'callback'),
		array('sid', 'checkSubject', '非法科目，请重新选择！', 1, 'callback'),
		array('cid', 'checkCate', '非法分类，请重新选择！', 1, 'callback'),
		array('uid', 'number', '非法用户，请填入正确的UID！', 2, 'regex'),
		array('uid', 'checkUid', '非法用户，请填入正确的UID！', 1, 'callback'),
		array('link', "checkUrl", '外部链接格式错误！', 1, 'callback'),
		array('title', 'require', '标题不能为空！', 1),
		array('title', '1,200', '标题长度过长！', 1, 'length'),
		array('content', "checkContent", '内容不能为空', 1, 'callback'),
		);
	protected $_auto = array(
		array('ctime', 'time', 1, 'function'),
		array('mtime', 'time', 1, 'function'),
		array('uid', "fillUid", 1, 'callback'),
		array('link', "fillUrl", 1, 'callback'),
		array('desc', "fillDesc", 1, 'callback'),
		);

	function checkGroup($gpid) {
		$id = intval($gpid);
		$group = M('GroupGroup');
		return $group -> where('id=' . $id) -> find() ? true : false;
	} 

	function checkGrade($gdid) {
		$gpid = intval(I('post.gpid'));
		$gdid = intval($gdid);
		$grade = M('GroupGrade');
		return $grade -> where(array('id' => $gdid, 'gid' => $gpid)) -> find() ? true : false;
	} 

	function checkSubject($sid) {
		$id = intval($sid);
		$subject = M('GroupSubject');
		return $subject -> where('id=' . $id) -> find() ? true : false;
	} 

	function checkCate($cid) {
		$res = intval(I('post.res'));
		$cid = intval($cid);
		$cate = M('GroupCategory');
		return $cate -> where(array('id' => $cid, 'res' => $res)) -> find() ? true : false;
	} 

	function checkUid($uid) {
		$id = intval($uid);
		if (isEmpty($id)) return true;
		$user = M('User');
		return $user -> where('id=' . $id) -> find() ? true : false;
	} 

	function checkUrl($link) {
		if (isEmpty($link)) return true;
		return $this -> regex($link, 'url');
	} 

	function fillUid() {
		$uid = I('post.uid');
		if (isEmpty($uid)) $uid = $_SESSION['uid'];
		return $uid;
	} 

	function fillUrl() {
		$link = I('post.link');
		if (isEmpty($link)) {
			$user = M('UserInfo');
			if (isEmpty($this -> data['uid'])) $this -> data['uid'] = $this -> fillUid();
			$userInfo = $user -> where('uid=' . $this -> data['uid']) -> find();
			$link = $userInfo ['site'];
			if (isEmpty($link)) $link = "http://study.zhuwei.cc";
		} 
		return $link;
	} 

	function checkContent($content) {
		$content = trim(strip_tags($content));
		return !isEmpty($content);
	} 

	function fillDesc() {
		$desc = I('post.desc');
		if (isEmpty($desc)) {
			$desc = cutStr(trim(strip_tags(str_replace('&nbsp;', '', html_entity_decode(I('post.content'))))), 200, '...');
		} 
		return $desc;
	} 

	function getData() {
		return $this -> data;
	} 
} 
